<?php
class OrderAction extends HomeAction
{
	public function _initialize()
	{
		parent::_initialize();
	}
	/**
	 * 订单查询
	 */
	public function query()
	{
		
		if($_POST['act'] == 'act_order_query' || $_REQUEST['order_sn'] != '')
		{
			if(C('vcode_order_query') && isset($_POST['order_query_vcode'])){
				if($_SESSION['order_query_vcode'] != strtolower($_POST['order_query_vcode'])){
					$this->error(L('_VERIFICATION_ERROR_'), url('order/query'));
				}
			}
			
			$order_sn = trim($_REQUEST['order_sn']);
			$orderInfo = OrderModel::get_oreder_info_by_order_sn($order_sn);
			//dump($orderInfo);exit;
			if(!$orderInfo){
				$this->error(L('_PRODUCT_NO_EXIST_'), url('order/query'));
			}else{
				 //订单产品列表
				$orderInfo['productList'] = OrderModel::get_order_product_list($orderInfo['id']);
				//发货单列表
				$orderInfo['deliveryList'] = OrderModel::get_delivery_list($orderInfo['id']);
				$expless_form = null;
				if($order['shipping_no']){
					import('COM.Express');
					$expless = new Express($order['shipping_method']);
					$expless_form = $expless->query($order['shipping_no']);
				}
				$orderInfo['expless_form'] = $expless_form;
				$this->assign('order', $orderInfo);
				//dump($orderInfo);exit;
				//查询订单中是否有商品已经下架
				$order_down_product = orderModel::get_order_product_isdown($orderInfo['id']);
				$this->assign('order_down_product', $order_down_product);
				//支付按钮
				if($orderInfo['payment_status'] == OrderModel::PAY_UNPAYED && ($orderInfo['order_status'] == OrderModel::ORDER_UNCONFIRMED || $orderInfo['order_status'] == OrderModel::ORDER_CONFIRMED)){
					//有产品下架的情况下不让支付
					if(!$order_down_product){
						import('COM.Payment');
						$paymentInstance = Payment::getInstance($orderInfo['payment_method']);
						$payOrderInfo = $orderInfo;
			            $payOrderInfo['currency'] = isset($_SESSION['currency']) && $_SESSION['currency'] ? $_SESSION['currency'] : C('currency'); //币种
			            $payOrderInfo['pay_amount'] = currency($orderInfo['pay_amount'],null,false);
						$paymentSubmit = $paymentInstance->getSubmitForm($payOrderInfo);
						$this->assign('paymentSubmit', $paymentSubmit);
					}
				}
				$this->display('query_info');
			}
		}
		else{
			$articleInfo = ArticleModel::get_article_info(4);
			$this->assign('articleInfo', $articleInfo);
			$this->display('query');
		}
	}
	
	//订单修改
	public function order_edit()
	{
        global $user;

		$order_id = intval($_GET['oid']);
		$orderInfo = OrderModel::get_order_info($order_id);
		$userType = 'user';
		if(isset($user['is_partner']) && $user['is_partner'] == 1){
		    $userType = 'partner';
		}
		if(!$orderInfo){
			if(UserModel::logged()){
			    $this->error(L('_PRODUCT_NO_EXIST_'), url($userType.'/order_list'));
		    }else{
		    	$this->error(L('_PRODUCT_NO_EXIST_'), url('order/query'));
		    }
		}else if(!UserModel::logged() && $orderInfo['user_id'] > 0){
			//当没登陆修改有user_id的订单时，提示登陆
           $this->error(L('_USER_NO_LOGINED_'), url($userType.'/login', 'src='.base64_encode(url($userType.'/order_list')))); 
		}else if(UserModel::logged() && $orderInfo['user_id'] > 0 && $orderInfo['user_id'] != $user['id']){
           //当登陆的情况下修改有user_id的订单，但订单不是他自己的，提示没权限
           $this->error(L('ordernotyou'), url($userType.'/order_list'));
		}
		
		if($orderInfo['payment_status'] != OrderModel::PAY_UNPAYED){
			$this->error(L('_PROHIBITION_MODIFY_'), $_SERVER['HTTP_REFERER']);
		}
		
		if($_POST['dosubmit']){
			
			//验证token
			if($_POST['ordertoken'] != OrderModel::get_order_token())
			{
				$this->error(L('_TOKEN_ERROR_'), url('order/order_edit', 'oid='.$order_id));
			}
			//如果是合作伙伴订单则不能修改email
			if($user['is_partner'] == 1){
				$_POST['delivery_email'] = $user['email'];
			}
			OrderModel::update_order($order_id, $_POST);
			if(UserModel::logged()){
			    $this->success(L('_ORDER_EDIT_SUCCESS_'), url($userType.'/order_info', 'oid='.$order_id));
		    }else{
		    	$this->success(L('_ORDER_EDIT_SUCCESS_'), url('order/query', 'order_sn='.$orderInfo['order_sn']));
		    }			
		}else{
		
			$orderInfo['productList'] = OrderModel::get_order_product_list($order_id);
			
			$orderToken = OrderModel::get_order_token();
			$this->assign('ordertoken', $orderToken);
			$addressList = UserModel::get_address_list($orderInfo['user_id']);
			$this->assign('addressList', $addressList);
			$paymentList = PaymentModel::get_payment_list();
			$this->assign('paymentList', $paymentList);
			$shippingList = ShippingModel::get_shipping_list();
			$this->assign('shippingList', $shippingList);
			$countryList = SiteModel::get_country_list();
			$this->assign('countryList', $countryList);
			
			$this->assign('orderInfo', $orderInfo);
			
			$this->display('order_edit');
		}
		
	}
	
	public function order_item_delete()
	{
		$order_id = intval($_GET['oid']);
		$oiid = intval($_GET['oiid']);
		$orderInfo = OrderModel::get_order_info($order_id);
		if(!$orderInfo){
			$this->error(L('_ORDER_NO_EXIST_'), url('user/order_list'));
		}
		$order_items_db = D('order_items');
		$order_items_db->delete($oiid);
		OrderModel::update_order_prices($order_id);
		$this->success(L('_OPERATION_SUCCESS_'), url('order/order_edit', 'oid='.$order_id));
	}
	
	/**
	 * 修改订单状态
	 */
	public function order_edit_status()
	{
		global $user,$language_id;
		if(!UserModel::logged()){
			redirect(url('user/login'));
		}
		$userType = 'user';
		if(isset($user['is_partner']) && $user['is_partner'] == 1){
		    $userType = 'partner';
		}		
		$order_id = intval($_GET['oid']);
		$status = trim($_GET['status']);
		//只能取消或者完成
		if(!in_array($status, array(OrderModel::ORDER_CANCELED, OrderModel::ORDER_COMPLETE)))
		{
			$this->error(L('_ILLEGAL_OPERATION_'), url($userType.'/order_list'));
		}
		$orderInfo = OrderModel::get_order_info($order_id);
		if(!$orderInfo){
			$this->error(L('_ORDER_NO_EXIST_'), url($userType.'/order_list'));
		}

		$order_db = D('orders');

		//取消
		if($status == OrderModel::ORDER_CANCELED){
	  	OrderModel::returned_order_surplus_and_points($order_id);

		//发送取消订单邮件
			$orderInfo = OrderModel::get_order_info($order_id);
			$mailInstance = new EmailModel();
			$email_template = UserModel::get_email_template_info('orderCancelEmail', $orderInfo['language_id']);
			if($email_template){
				$content = $mailInstance->replaceMail($email_template['content'], $orderInfo);
				$title = $mailInstance->replaceMail($email_template['title']);
				$mailInstance->sendMail($post['delivery_email'], $title, $content);
			}
		}
		//完成
		elseif($status == OrderModel::ORDER_COMPLETE){
			//屏蔽错误发送退款邮件BUG OrderModel::returned_part_order_points($order_id);	
		}
		if($status==2){
			$order_edit_data = array('order_status' => $status,'shipping_status'=>2);
		}else{
			$order_edit_data = array('order_status' => $status);
		}

		if($status == 2){
            $order_edit_data['end_time'] = time();
		}
		$affter = $order_db->where(array('id' => $order_id))->save($order_edit_data);
		if($affter){
			$logData = array(
	  		'order_id' => $order_id,
		  	'order_status' => $status,
		  	'payment_status' => $orderInfo['payment_status'],
		  	'shipping_status' => $orderInfo['shipping_status'],
	  		'action_notice' => $post['action_notice'] ? trim($post['action_notice']) : null,
	  		'action_name' => $user['username'],
			);
			
			OrderModel::insert_orders_log($logData);
			if($orderInfo['is_gift_orders']==1){
				$this->success(L('_OPERATION_SUCCESS_'), url($userType.'/order_list',array('is_gift_orders'=>1)));
			}else{
				$this->success(L('_OPERATION_SUCCESS_'), url($userType.'/order_list'));
			}
            //订单完成短信
            $ShortMessage=A("ShortMessage");
            $result=$ShortMessage->send_message('SMS_4690564',$orderInfo['delivery_phone'],'{"order_sn":"'.$orderInfo['order_sn'].'"}');
            if($result){
                Log::write('订单完成短信，订单号：'.$orderInfo['order_sn'].'，时间：'.date("Y-m-d H:i:s",time()));
            }
		}else{
			if($orderInfo['is_gift_orders']==1){
				$this->error(L('_OPERATION_FAIL_'), url($userType.'/order_list',array('is_gift_orders'=>1)));
			}else{
				$this->error(L('_OPERATION_FAIL_'), url($userType.'/order_list'));
			}

		}
	}
	
	//预售申请退款
	public function order_refund()
	{
		global $user;
		
		if(! UserModel::logged()){
			redirect(url('user/login'),'', L('_USER_NO_LOGINED_'));
		}
		
		$order_id = intval($_GET['oid']);
		
		$order_items_db = D('orders_items oi');
		$order_items_db->field('delivery_first_name,delivery_last_name,delivery_phone,delivery_email,orders.order_sn,orders.order_amount,orders.integral_money,orders.integral,orders.payment_method,oi.id AS orders_items_id,oi.order_id,oi.product_name,oi.product_id,product.small_img,product.refund,product.yufu_price,oi.pay_price,oi.qty,oi.total_amount');
		$order_items_db->join('orders ON orders.id = oi.order_id');
		$order_items_db->join('product ON product.id = oi.product_id');
		$orderInfo = $order_items_db->where('oi.order_id='.$order_id)->find();
		if(!$orderInfo)
			$this->error(L('_PRODUCT_NO_EXIST_'), url('user/order_info', array('oid' => $order_id)));
		
		if($orderInfo['refund']){
			$post['return_amount'] = $orderInfo['order_amount'] - ($orderInfo['yufu_price']*$orderInfo['qty']) - $orderInfo['integral_money'];
			$post['return_rank_points'] = $orderInfo['integral'];
			$post['admin_note'] = L('_ORDER_REFUND_').'，'.L('_THE_ORDER_NUMBER_IS_').'：'.$orderInfo['order_sn'].'; '.L('payment_method').'：'.$orderInfo['payment_method'].','.L('already_back_into_balance').'.';
		}else{
			$post['return_amount'] = $orderInfo['order_amount'] - $orderInfo['integral_money'];
			$post['return_rank_points'] = $orderInfo['integral'];
			$post['admin_note'] = L('_ORDER_REFUND_').'，'.L('_THE_ORDER_NUMBER_IS_').'：'.$orderInfo['order_sn'].'; '.L('payment_method').'：'.$orderInfo['payment_method'].','.L('already_back_into_balance').'.';
		}
		
		
		
		$pay_return_db = D('orders_pay_return');
		$returnInfo = $pay_return_db->where('order_sn="'.$orderInfo['order_sn'].'" AND car_type=1')->find();
		
		if($returnInfo){
			$this->error(L('the_order_is_filed'), url('user/order_info', array('oid' => $order_id)));
		}
		
		$data = array(
			'return_amount' => floatval($post['return_amount']),
			'return_rank_points' => floatval($post['return_rank_points']),
			'admin_note' => trim($post['admin_note']),
			'admin_user' => 'system',
			'end_time' => time(),
			'status' => 0,
		);
			
		$data['user_id'] = $user['id'] ? $user['id'] : null;
		$data['user_name'] = $orderInfo['delivery_first_name'] ? $orderInfo['delivery_first_name'] : null;
		$data['order_id'] = $orderInfo['order_id'] ? $orderInfo['order_id'] : null;
		$data['order_sn'] = $orderInfo['order_sn'] ? $orderInfo['order_sn'] : null;
		$data['add_time'] = time();
		$data['car_type'] = 1;
		$pid = $pay_return_db->add($data);
		
		if($pid){
			$this->success(L('_OPERATION_SUCCESS_'), url('user/order_info', array('oid' => $order_id)));
		}else{
			$this->error(L('_OPERATION_FAIL_'), url('user/order_info', array('oid' => $order_id)));
		}

	}
	
	//ajax获取支付状态名称
	public function ajax_payment_name()
	{
		$psid = $_REQUEST['psid'];
		$result = array(
			'error' => 1,
			'psid' => $psid,
			'name' => null,
		);
		
		if($psid == ''){
			$payment_name = L('any');
		}else{
			$payment_name = L(OrderModel::$paymentStatus[''.$psid].'');
		}
		
		
		$result = array(
			'error' => 0,
			'psid' => $psid,
			'name' => $payment_name,
		);
		echo json_encode($result);exit;
	}
	
	//ajax获取订单状态名称
	public function ajax_order_name()
	{
		$osid = $_REQUEST['osid'];
		$result = array(
			'error' => 1,
			'osid' => $osid,
			'name' => null,
		);
		
		if($osid == ''){
			$order_name = L('any');
		}else{
			$order_name = L(OrderModel::$orderStatus[$osid]);
		}
		
		$result = array(
			'error' => 0,
			'osid' => $osid,
			'name' => $order_name,
		);
		echo json_encode($result);exit;
	}
}